package org.binglan.youziyuepai.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.binglan.youziyuepai.controller.base.BasicController;
import org.binglan.youziyuepai.entity.*;
import org.binglan.youziyuepai.enums.code.*;
import org.binglan.youziyuepai.form.PublishDatePatForm;
import org.binglan.youziyuepai.service.*;
import org.binglan.youziyuepai.utils.EnumUtils;
import org.binglan.youziyuepai.utils.ResponseVoUtils;
import org.binglan.youziyuepai.vo.DatePatApplyVo;
import org.binglan.youziyuepai.vo.DatePatVo;
import org.binglan.youziyuepai.vo.PageVo;
import org.binglan.youziyuepai.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/4/10 18:45
 */
@Api(tags = "约拍业务相关接口")
@RestController
@RequestMapping("/publishDatePat")
public class PublishDatePatController extends BasicController {

    @Autowired
    OccupationService occupationService;

    @Autowired
    PersonalDynamicService personalDynamicService;

    @Autowired
    PersonalDynamicApplyService personalDynamicApplyService;

    @Autowired
    UserService userService;

    @Autowired
    UserContactWayService userContactWayService;

    @Autowired
    ImageService imageService;

    @ApiOperation(value = "发布约拍", notes = "发布约拍")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string")
    })
    @PostMapping("")
    public ResponseVo create(@RequestBody PublishDatePatForm publishDatePatForm,
                             BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseVoUtils.error(bindingResult);
        }
        // 判断 condition 是否存在
        Integer condition = publishDatePatForm.getDatePatCondition();
        if (!EnumUtils.isExistsCode(condition, AcceptDatePatConditionEnum.class)) {
            return ResponseVoUtils.error("不存在该 condition");
        }
        // 判断 costType 是否存在
        Integer costType = publishDatePatForm.getCostType();
        if (!EnumUtils.isExistsCode(costType, ContactTypeEnum.class)) {
            return ResponseVoUtils.error("不存在该 costType");
        }
        // 判断 costType = 3 ，money 是否合法
        Integer money = publishDatePatForm.getMoney();
        if (costType == 3 && (money == null || money == 0)) {
            return ResponseVoUtils.error("costType = 3, money不能为空");
        }
        // 判断需求职业id是否存在
        Integer occupationId = publishDatePatForm.getOccupationId();
        if (!occupationService.isExistsIds(Collections.singletonList(occupationId))) {
            return ResponseVoUtils.error("不存在该职业id");
        };

        String userId = this.getUserIdByAuth();


        PersonalDynamic personalDynamic = new PersonalDynamic();
        BeanUtils.copyProperties(publishDatePatForm, personalDynamic);
        // 是否允许发布(0 不允许,1 允许) 默认不允许
        personalDynamic.setIsAllow(1);
        personalDynamic.setUserId(userId);
        List<String> imageIds = publishDatePatForm.getImageIds();


        personalDynamicService.savePersonalDynamic(personalDynamic, imageIds);

        return ResponseVoUtils.success();
    }


    @ApiOperation(value = "删除用户的约拍信息", notes = "删除用户的约拍信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "personalDynamicId", value = "动态id", required = true, paramType = "header", dataType = "string")
    })
    @DeleteMapping(value = "")
    public ResponseVo deleteUserDatePat(String personalDynamicId) {
        String userId = this.getUserIdByAuth();

        Boolean isDelete = personalDynamicService.deletePersonalDynamicByPersonalDynamicId(personalDynamicId, userId);
        return ResponseVoUtils.success();
    }


    @ApiOperation(value = "主页约拍信息数据接口", notes = "主页约拍信息数据接口(分页)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "size", value = "每页数据数量", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "occupationId", value = "约拍类型(1 模特，2 摄影师，默认查询所有信息)", required = false, paramType = "query", dataType = "string")
    })
    @GetMapping(value = "")
    public ResponseVo getDatePats(@RequestParam(value = "page",defaultValue = "1") Integer page,
                                  @RequestParam(value = "size",defaultValue = "5") Integer size,
                                  @RequestParam(value = "occupationId",defaultValue = "-1") Integer occupationId) {

        PageVo<DatePatVo> pageVo = personalDynamicService.queryDatePatByPage(new Page<PersonalDynamic>(page, size), AllowEnum.ALLOW.getCode(), occupationId);
        return ResponseVoUtils.success(pageVo);
    }

    @ApiOperation(value = "发起约拍申请接口", notes = "发起约拍申请接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "datePatId", value = "个人动态id", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "datePatReason", value = "申请约拍理由", required = true, paramType = "query", dataType = "string"),
    })
    @PostMapping(value = "/apply")
    public ResponseVo sendDatePatApply(@RequestParam String datePatId, String datePatReason) {
        String userId = this.getUserIdByAuth();

        // 参数验证
        if (StringUtils.isBlank(datePatId)) {
            return ResponseVoUtils.error("datePatId 不能为空");
        }
        if (StringUtils.isBlank(datePatReason)) {
            return ResponseVoUtils.error("datePatReason 不能为空");
        }
        personalDynamicService.sendDatePatApply(userId, datePatId,datePatReason);
        return ResponseVoUtils.success();
    }

    @ApiOperation(value = "获取用户收到的约拍请求", notes = "获取用户收到的约拍请求接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @GetMapping(value = "/apply/receive")
    public ResponseVo getDatePatReceiveApply() {
        String userId = this.getUserIdByAuth();
        List<DatePatApplyVo> datePatApplyVos = new ArrayList<>();

        // 查询用户收到的约拍申请
        List<PersonalDynamicApply> personalDynamicApplies = personalDynamicApplyService.queryReceivePersonalDynamicApplyByUserId(userId);

        personalDynamicApplies.forEach(apply -> {
            DatePatApplyVo vo = new DatePatApplyVo();
            vo.setUserVo(userService.queryUserVoByUserId(apply.getApplyUserId()));
            vo.setPersonalDynamicApply(apply);
            vo.setPersonalDynamic(personalDynamicService.queryByPersonalDynamicId(apply.getPersonalDynamicId()));
            vo.setUsetContactWayVo(userContactWayService.queryUserContactWayVoByUserId(apply.getApplyUserId()));
            datePatApplyVos.add(vo);
        });

        return ResponseVoUtils.success(datePatApplyVos);
    }

    @ApiOperation(value = "获取用户发送的约拍请求", notes = "获取用户发送的约拍请求接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @GetMapping(value = "/apply/send")
    public ResponseVo getDatePatSendApply() {
        String userId = this.getUserIdByAuth();
        List<DatePatApplyVo> datePatApplyVos = new ArrayList<>();

        // 查用户发送的约拍请求
        List<PersonalDynamicApply> personalDynamicApplies = personalDynamicApplyService.querySendPersonalDynamicApplyByUserId(userId);

        personalDynamicApplies.forEach(apply -> {
            DatePatApplyVo vo = new DatePatApplyVo();
            PersonalDynamic personalDynamic = personalDynamicService.queryByPersonalDynamicId(apply.getPersonalDynamicId());
            vo.setPersonalDynamic(personalDynamic);
            vo.setPersonalDynamicApply(apply);
            vo.setUserVo(userService.queryUserVoByUserId(personalDynamic.getUserId()));
            datePatApplyVos.add(vo);
        });

        return ResponseVoUtils.success(datePatApplyVos);
    }

    @ApiOperation(value = "接受用户约拍请求", notes = "接受用户约拍请求接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "applyId", value = "约拍请求id", required = true, paramType = "query", dataType = "string"),

    })
    @GetMapping(value = "/apply/accept")
    public ResponseVo acceptDatePatApply(Integer applyId) {
        String userId = this.getUserIdByAuth();

        personalDynamicApplyService.changeDatePatApplyStatus(userId, applyId, StatusEnum.ACCEPT);

        return ResponseVoUtils.success();
    }

    @ApiOperation(value = "拒绝用户约拍请求", notes = "拒绝用户约拍请求接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "applyId", value = "约拍请求id", required = true, paramType = "query", dataType = "string"),

    })
    @GetMapping(value = "/apply/refuse")
    public ResponseVo refusetDatePatApply(Integer applyId) {
        String userId = this.getUserIdByAuth();

        personalDynamicApplyService.changeDatePatApplyStatus(userId, applyId, StatusEnum.REFUSE);

        return ResponseVoUtils.success();
    }

    @ApiOperation(value = "获取用户发送约拍记录", notes = "获取用户发送约拍记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @GetMapping(value = "/getUserDatePats")
    public ResponseVo getUserDatePats() {
        String userId = this.getUserIdByAuth();
        List<DatePatApplyVo> datePatApplyVos = new ArrayList<>();

        List<PersonalDynamic> personalDynamics = personalDynamicService.queryPersonalDynamicsByUserId(userId);
        List<DatePatVo> collect = personalDynamics.stream().map(item -> {
            DatePatVo datePatVo = new DatePatVo();
            datePatVo.setUserVo(userService.queryUserVoByUserId(item.getUserId()));
            BeanUtils.copyProperties(item, datePatVo);
            datePatVo.setCostTypeName(EnumUtils.getMessageByCode(item.getDatePatCondition(), CostTypeEnum.class));
            datePatVo.setDatePatConditionName(EnumUtils.getMessageByCode(item.getDatePatCondition(),AcceptDatePatConditionEnum.class));
            datePatVo.setImages(imageService.queryImageByPersonalDynamicId(item.getId()));

            datePatVo.setOccupation(occupationService.queryOccupationById(item.getOccupationId()));
            return datePatVo;
        }).collect(Collectors.toList());

        return ResponseVoUtils.success(collect);
    }

}
